#include "relay.h"
#include "drv_common.h"

relay_dev_t relay_array[] = {
    { // CH0
        .pin = GPIO_Pin_13,
        .port = GPIOC,
        .active_low = 1,
    }, { // CH1
        .pin = GPIO_Pin_8,
        .port = GPIOA,
        .active_low = 1,
    }
};

void relay_init(void)
{
    int i;
    GPIO_InitTypeDef GPIO_InitStructure;

    RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_GPIOC, ENABLE);

    for (i = 0; i < ARRAY_SIZE(relay_array); i++) {
        GPIO_InitStructure.GPIO_Pin = relay_array[i].pin;
        GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
        GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
        GPIO_Init(relay_array[i].port, &GPIO_InitStructure);
        
        GPIO_WriteBit((relay_array + i)->port, (relay_array + i)->pin, (BitAction)((relay_array + i)->active_low));
    }
}

void relay_on(relay_dev_t *dev)
{
    GPIO_WriteBit(dev->port, dev->pin, (BitAction)!(dev->active_low));
}

void relay_off(relay_dev_t *dev)
{
    GPIO_WriteBit(dev->port, dev->pin, (BitAction)(dev->active_low));
}

void relay_op(relay_dev_t *dev, int operation)
{
    GPIO_WriteBit(dev->port, dev->pin, (BitAction)(dev->active_low ^ operation));
}
